/*
 * Copyright 1994, Black Adder Research, Inc.  This source code may be
 * redistributed and modified with one restriction - do not claim that 
 * you wrote it.
 *
 * Black Adder Research, Inc.
 * 730 Norell Ave. North
 * Stillwater, MN  55082
 * 
 */


#import "AVIView.h"
#import <appkit/appkit.h>

@implementation AVIView : View

- initSize: (const NXSize *) aSize
{
    NXRect imageRect;
	id retVal = nil;

	NXSetRect(&imageRect, 0.0, 0.0, aSize->width, aSize->height);
    [super initFrame:&imageRect];
	strcpy(aviFile, "");
	if((theData = (unsigned char *)malloc(3 * (int) (aSize->width * aSize->height))) != NULL) {
		if((theBitmap = [[NXBitmapImageRep alloc] initData:theData
			pixelsWide: (int) aSize->width
			pixelsHigh: (int) aSize->height
			bitsPerSample: 8
			samplesPerPixel: 3
			hasAlpha: NO
			isPlanar: NO
			colorSpace: NX_RGBColorSpace
			bytesPerRow: 0
			bitsPerPixel: 0]) != nil) {
	
				retVal = self;
		}
	}
    return(retVal);
}


- runFromFile: (char *) AVIFile
{
	strcpy(aviFile, AVIFile);
	[self runAgain];
	return(self);
}


- runAgain
{
	char command[256];
	int numFrPix;
	BOOL shouldLoop = YES;
	FILE *ifp;

	if (strcmp(aviFile, "") != 0) {
		numFrPix = 3 * [theBitmap pixelsWide] * [theBitmap pixelsHigh];
		sprintf(command, "%s/aviDecode %s", [[NXBundle mainBundle] directory], aviFile);
		if ((ifp = popen(command, "r")) != NULL) {			
			fread(theData, 1, 2*sizeof(int), ifp);	/* skip width and height */
			[self lockFocus];
			while(shouldLoop) {
				if(NXUserAborted()) {
					NXResetUserAbort();
					if(NX_ALERTDEFAULT == NXRunAlertPanel("AVIStream", 
							"Stop Playback?", "Yes", "No", NULL) ) {
						shouldLoop = NO;
						break;
					}
				}
				if(fread(theData, 1, numFrPix, ifp) != numFrPix) {
					shouldLoop = NO;
					break;
				}
				else {
					[theBitmap draw];
					NXPing();
				}
			}
			[self unlockFocus];
			pclose(ifp);
		}
	}
	return(self);
}


- drawSelf:(const NXRect *)rects :(int)rectCount
{
    [theBitmap draw];
    return self;
}


- free
{
	free(theData);
	[theBitmap free];
    return [super free];
}

@end
